const {
	db,
	dbCmd,
	result_success,
	result_error,
	appletInfoCollection,
	shopieCollection,
	shopieReportCollection,
	shopieUserReportCollection,
	userCollection
} = require('../../common/constants')
module.exports = async function(params = {}) {
	const token = this.getUniIdToken()
	if (!token) {
		return result_error('登录失效,请重新登录')
	}
	let payload = await this.uniID.checkToken(token)
	if (payload.code) {
		return payload
	}
	let cUser = await userCollection.doc(payload.uid).get()
	cUser = cUser.data[0]
	if(!cUser.app_id){
		return result_success({})
	}
	//获取当前应用
	let appletInfoData = await appletInfoCollection.doc(cUser.app_id).get()
	appletInfoData = appletInfoData.data[0]
	let role = cUser.role[0]

	let limit = params.limit
	let skip = params.skip
	let startDate = params.startDate
	let endDate = params.endDate
	let startDateTime;
	let endDateTime;
	let timezone = 8;
	let calDateTime = timezone * 60 * 60 * 1000;
	if (startDate) {
		if (!endDate) {
			endDate = startDate
		}
		startDate = new Date(startDate + ' 00:00:00');
		endDate = new Date(endDate + ' 23:59:59');
		if (startDate && startDate.toString().indexOf('UTC') > -1) {
			startDateTime = startDate.getTime() - calDateTime;
			endDateTime = endDate.getTime() - calDateTime;
		} else {
			startDateTime = startDate.getTime();
			endDateTime = endDate.getTime();
		}
	}
	let queryParams = {
		app_id: appletInfoData._id,
		shop_id: appletInfoData._id
	};

	let rData = []
	for (var i = 0; i < limit; i++) {
		if (skip === 0) {
			if (i > 0) {
				startDate.setDate(startDate.getDate() - 1)
			}
		} else {
			startDate.setDate(startDate.getDate() - 1)
		}
		let cYear = startDate.getFullYear();
		let cMonth = startDate.getMonth() + 1;
		let cDay = startDate.getDate();
		queryParams.year = cYear
		queryParams.month = cMonth
		queryParams.day = cDay
		let shopieRepostData
		if (role === 'shop_admin') {
			shopieRepostData = await shopieReportCollection.where(queryParams)
				.limit(limit)
				.orderBy('create_time', 'desc')
				.get()
		} else {
			queryParams.share_user_id = cUser._id
			shopieRepostData = await shopieUserReportCollection.where(queryParams)
				.limit(limit)
				.orderBy('create_time', 'desc')
				.get()
		}
		shopieRepostData = shopieRepostData.data
		if (shopieRepostData.length > 0) {
			let shopieData = shopieRepostData[0].data
			let refound_money = 0
			if (shopieRepostData[0].refound_money) {
				refound_money = shopieRepostData[0].refound_money
			}
			let total_money = shopieRepostData[0].money - refound_money
			rData.push({
				money: total_money,
				count: shopieRepostData[0].count,
				data: shopieData,
				day: queryParams.month + "-" + queryParams.day
			})
		} else {
			rData.push({
				money: 0,
				count: 0,
				data: [],
				day: queryParams.month + "-" + queryParams.day
			})
		}
	}
	return result_success({
		rData: rData,
		startDate: queryParams.year + "-" + queryParams.month + "-" + queryParams.day
	})
}